<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\handlers\impl;

use lflow\helper\ProxyHelper;
use lflow\implement\SchedulerInterceptor;
use lflow\Logger;
use lflow\workflow\Execution;
use lflow\handlers\IHandler;
use lflow\model\TaskModel;
use lflow\WorkFlowException;
use lflow\WorkFlowInterceptor;
use ReflectionClass;

/**
 * 任务创建操作处理器
 *
 * @author Mr.April
 * @since  1.0
 */
class CreateTaskHandler implements IHandler
{

    /**
     * @var \lflow\model\TaskModel 任务模型
     */
    private TaskModel $model;

    /**
     * 调用者需要提供用户模型
     *
     * @param \lflow\model\TaskModel $model 任务模型
     */
    public function __construct(TaskModel $model)
    {
        $this->model = $model;
    }

    /**
     * 根据任务模型、执行对象，创建下一个任务，并添加到execution对象的tasks集合中
     *
     * @param \lflow\workflow\Execution $execution
     *
     * @throws \lflow\WorkFlowException
     */
    public function handle(Execution $execution): void
    {
        //创建任务task步骤
        $tasks = $execution->getEngine()->task()->createTask($this->model, $execution);
        $execution->addTasks($tasks);
        //从服务上下文中查找任务拦截器列表，依次对task集合进行拦截处理
        try {
            new SchedulerInterceptor();
            $classes = get_declared_classes();
            foreach ($classes as $klass) {
                $reflect = new ReflectionClass($klass);
                if ($reflect->implementsInterface(WorkFlowInterceptor::class)) {
                    $interceptor = new ProxyHelper($klass);
                    $interceptor->intercept($execution);
                }
            }
        } catch (\Exception $e) {
            Logger::error("拦截器执行失败=" . $e->getMessage());
            throw new WorkFlowException($e);
        }
    }
}
